package com.hjimi.ski.utils.update;

import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import org.lzh.framework.updatepluginlib.UpdateBuilder;
import org.lzh.framework.updatepluginlib.base.CheckNotifier;
import org.lzh.framework.updatepluginlib.model.Update;


/**
 * 简单实现：使用通知对用户提示：检查到有更新
 */
public class NotificationUpdateCreator extends CheckNotifier {
    private final static String ACTION_UPDATE = "action.update.shot";
    private final static String ACTION_CANCEL = "action.update.cancel";
    private RequestUpdateReceiver requestUpdateReceiver;
    private Update update;
    private UpdateBuilder builderWM;
    NotificationManager manager;
    NotificationUpdateCreatorI notificationUpdateCreatorI;
    int id;
    private String mCurVersionName;  //版本名称
    private int mCurVersionCode;     //版本号

    public NotificationUpdateCreator(UpdateBuilder builderWM,
                                     String mCurVersionName,
                                     int mCurVersionCode,
                                     NotificationUpdateCreatorI notificationUpdateCreatorI) {
        this.builderWM = builderWM;
        this.notificationUpdateCreatorI = notificationUpdateCreatorI;
        this.mCurVersionName = mCurVersionName;
        this.mCurVersionCode = mCurVersionCode;
    }

    @Override
    public Dialog create(Activity context) {
        requestUpdateReceiver = new RequestUpdateReceiver();
        registerReceiver(context);
        createNotification(context);
        this.update = update;

        // 由于需要使用通知实现。此处返回null即可
        return null;
    }

    private void createNotification(Context context){

    }

    public class RequestUpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent);
            unregisterReceiver(context);
            if (ACTION_UPDATE.equals(intent.getAction())) {
                // 发送下载请求。继续更新流程
                sendDownloadRequest();
            } else {
                // 中断更新流程并通知用户取消更新
                sendUserCancel();
            }
            manager.cancel(id);
        }
    }

    private void registerReceiver (Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_UPDATE);
        filter.addAction(ACTION_CANCEL);
        context.registerReceiver(requestUpdateReceiver, filter);
    }

    private void unregisterReceiver (Context context) {
        context.unregisterReceiver(requestUpdateReceiver);
    }


    public interface NotificationUpdateCreatorI{

        void onClick(int button);
        void isNotMandatory();


    }
}
